// http://api.my531.com/Login/?username=用户名&password=密码

import axios from "axios"
import { toFail, toSuccess, useEntityManager } from "@sker/core"
import { useAddonSetting } from "@sker/runtime"
import { SysAddon } from "@sker/entities";

export default async () => {
    // 检查权限
    return await useEntityManager(async m => {
        const coreSetting = await useAddonSetting(`@autojs/core`)
        if (coreSetting.smsToken) return toSuccess(true)
        const one = await m.findOne(SysAddon, { where: { name: '@autojs/core' } })
        if (!one) return toFail(`操作失败`)
        const token = await getToken()
        if (!token) return toFail(`操作失败`)
        await m.update(SysAddon, one.id, {
            setting: {
                ...one.setting,
                smsToken: token
            }
        })
        return toSuccess(true)
    })
}


function getToken(): Promise<string | undefined> {
    const url = `http://api.my531.com/Login/?username=imeepos&password=yang1989.&type=json`
    return axios.get(url).then(res => res.data).then(res => {
        if (res.stat) {
            const { token } = res.data;
            return token;
        }
    })
}
